package example.org;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Environment;
import android.widget.Toast;

public class CobaReceiver extends BroadcastReceiver {
	@Override
	public void onReceive(Context context, Intent intent) {
		if (Resource.isFirstStart) {
			Resource.isFirstStart = false;
		} else {
			Runtime runtime = Runtime.getRuntime();
			String cmd = "screenshot";
			Process proc = null;
			OutputStreamWriter osw = null;

			try {
				proc = runtime.exec("su");
				osw = new OutputStreamWriter(proc.getOutputStream());
				osw.write(cmd);
				osw.flush();
				osw.close();

				if (Resource.ReadSetting()) {
					MediaPlayer mPlayer = MediaPlayer.create(context,
							R.raw.camera);
					mPlayer.start();
				}
				
				Thread.sleep(500);

				// Copy File
				File src = new File(Environment.getExternalStorageDirectory()
						+ "/tmpshot.bmp");
				File dst = new File(Resource.savePath + "/"
						+ System.currentTimeMillis() + ".png");

				copyFile(src, dst);
				src.delete();

				Intent i = new Intent();
				i.setClassName("example.org", "example.org.EditImage");
				i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				i.putExtra("gambar", "file:///" + dst.getAbsolutePath());
				context.startActivity(i);
			} catch (Exception e) {
				Toast.makeText(context, "Failed to Take Screenshot",
						Toast.LENGTH_SHORT).show();
			}
		}
	}

	protected void copyFile(File src, File dst) throws Exception {
		InputStream in = new FileInputStream(src);
		OutputStream out = new FileOutputStream(dst);

		// Transfer bytes from in to out
		byte[] buf = new byte[1024];
		int len;

		while ((len = in.read(buf)) > 0) {
			out.write(buf, 0, len);
		}

		in.close();
		out.close();
	}
}
